package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    FileStorageService fileStorageService;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }
        //检查用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //检查文件上传格式
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        //上传文件到oss
        String file = null;
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            file = fileStorageService.store(prefix,uuid+suffix,multipartFile.getInputStream());
        }catch (Exception e){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器内部错误,图片上传失败");
        }

        //新增数据到WmMaterial
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(file);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite+file);
        //返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //参数检查
        dto.checkParam();
        //条件查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //收藏
        if (dto.getIsCollection()!=null||dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //当前登录用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //时间排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> materialPage = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> page = this.page(materialPage, wrapper);
        //给图片加上前缀访问路径
        List<WmMaterial> records = page.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        //返回的结果
        return ResponseResult.okResult(records);
    }

    @Autowired
    WmNewsMaterialMapper newsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //参数验证
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断图片是否被引用
        WmNewsMaterial newsMaterial = newsMaterialMapper.selectById(id);
        if (newsMaterial!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //删除素材库
        this.removeById(id);
        //删除图片
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short a) {
        //参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        Integer userId = user.getId();
        LambdaUpdateWrapper<WmMaterial> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(WmMaterial::getIsCollection,a).eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        this.update(wrapper);
        return ResponseResult.okResult();
    }

    /**
     * 检查文件格式
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path){
        if(StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
